<template>
  <div class="tags-body">
    <el-input v-model="label" class="tags-search" clearable placeholder="请输入标签名称" size="small" @clear="filterTags" @input="filterTags">
      <i slot="suffix" class="el-icon-search el-input__icon"></i>
    </el-input>
    <div class="list-container">
      <div class="tags-item-wrapper" v-for="item in tagsList" :key="item.value"  @click="selectTags(item)">
        <el-tag class="tag-item" v-if="checkActive(item.value)" type="success">{{ item.label }}</el-tag>
        <el-tag class="tag-item" v-else>{{ item.label }}</el-tag>
      </div>
      <el-empty v-if="tagsList.length === 0" description="暂无标签数据" class="empty"></el-empty>
    </div>
  </div>
</template>

<script>
import { listOptions } from '../../api/blog/blog-tags'

export default {
  name: 'TagsSelect',

  props: {
    // 激活的标签
    activeTags: {
      type: Array,
      require: true,
      default: () => []
    }
  },

  data () {
    return {
      // 标签名称
      label: '',
      // 标签集合
      tagsList: [],
      // 备用标签集合
      list: []
    }
  },

  mounted () {
    this.$nextTick(() => {
      this.listOptions()
    })
  },

  methods: {
    // 获取博客标签
    listOptions () {
      const that = this
      listOptions().then((res) => {
        that.tagsList = res
        that.list = res
      }).catch(() => {
        that.$message.error('博客标签数据获取异常')
      })
    },
    // 过滤标签集合
    filterTags () {
      // 获取标签内容
      this.tagsList = this.list
      if (this.label) {
        this.tagsList = this.tagsList.filter(item => item.label.includes(this.label))
      }
    },
    // 选择标签
    selectTags (tag) {
      this.$emit('selectTags', tag)
      // 在浏览器body进行点击操作隐藏选择框
      // document.body.click()
    },
    // 校验当前标签是否激活
    checkActive (id) {
      for (var i = 0; i < this.activeTags.length; i++) {
        if (this.activeTags[i].value === id) {
          return true
        }
      }
      return false
    },
    reset () {
      this.label = ''
      this.listOptions()
    }
  }
}
</script>

<style lang="scss" scoped>
.list-container {
  display: flex;
  flex-wrap: wrap;
  .tags-item-wrapper {
    overflow-x: hidden;
    cursor: pointer;
    display: flex;
    margin-right: 0.5rem;
    margin-bottom: 0.5rem;
  }
  .empty {
    width: 100%;
  }
}
.tags-body {
  width: 100%;
  .tags-search {
    position: relative;
    margin-bottom: 1rem;
  }
}
.tag-item {
  display: flex;
  max-width: 100%;
  height: 100%;
}
</style>
